﻿/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     public int val;
 *     public ListNode next;
 *     public ListNode(int val=0, ListNode next=null) {
 *         this.val = val;
 *         this.next = next;
 *     }
 * }
 */
public class ListNode {
    public int val;
    public ListNode next;
    public ListNode(int val=0, ListNode next=null) 
    { 
        this.val = val;
        this.next = next;
    }
}
public class Solution {
    public ListNode RemoveElements(ListNode head, int val)
    {
        // 判空
        if (head is null)
        {
            return head;
        }
            
        ListNode pre = head;
        while (pre.next is not null)
        {
            // 删除节点
            if (pre.next.val == val)
            {
                pre.next = pre.next.next;
            }
            else
            {
                pre = pre.next;
            }
        }
        // 最后判断头节点的值
        if (head.val == val)
        {
            head = head.next;
        }
        return head;
    }

    public static void Main(string[] args)
    {
        int[] head = [1, 2, 6, 3, 4, 5, 6];
        int val = 6;
        
        // 构建链表
        ListNode headNode = new ListNode();
        ListNode pre = headNode;
        foreach (int h in head)
        {
            ListNode l = new ListNode(h);
            pre.next = l;
            pre = pre.next;
        }

        Solution solution = new Solution();
        headNode.next = solution.RemoveElements(headNode.next, val);
        pre = headNode;
        while (pre.next is not null)
        {
            Console.Write($"{pre.next.val} ");
            pre = pre.next;
        }
    }
}